package com.hsogoo.ultraman.spi;

import java.util.Map;

import com.google.common.collect.Maps;
import com.hsogoo.ultraman.ConfigFactory;
import com.hsogoo.ultraman.ConfigFactoryRegistry;
import com.hsogoo.ultraman.container.ConfigContainer;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by za-huangsaigang on 2018/9/20.
 */
@Slf4j
public class DefaultConfigFactoryRegistry implements ConfigFactoryRegistry {

    private Map<String, ConfigFactory> factories = Maps.newConcurrentMap();

    @Override
    public void register(String namespace, ConfigFactory factory) {
        if (factories.containsKey(namespace)) {
            log.info("ConfigFactory({}) is overridden by {}!", namespace, factory.getClass());
        }
        factories.put(namespace, factory);
    }

    @Override
    public ConfigFactory getFactory(String namespace) {
        //from cache
        ConfigFactory factory = factories.get(namespace);
        if(factory != null){
            return factory;
        }

        //new factory
        factory = ConfigContainer.getBean(ConfigFactory.class);

        //add to cache
        factories.put(namespace, factory);

        return factory;
    }

}
